package cc.cix.hq.common.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 填充器
 *
 * @author cix
 */
public class BaseMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入数据时，自动添加创建时间与更新时间字段
     */
    @Override
    public void insertFill(final MetaObject metaObject) {
        // 插入
        final Class<?> createdTime;
        try {
            createdTime = metaObject.getSetterType("createTime");
        } catch (final Exception e) {
            return;
        }
        if (createdTime.isAssignableFrom(LocalDateTime.class)) {
            setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        } else {
            setFieldValByName("createTime", LocalDate.now(), metaObject);
        }
    }

    /**
     * 更新数据时，自动修改更新时间字段
     */
    @Override
    public void updateFill(final MetaObject metaObject) {
        final Class<?> updatedTime;
        try {
            updatedTime = metaObject.getSetterType("updateTime");
        } catch (final Exception e) {
            return;
        }
        if (updatedTime.isAssignableFrom(LocalDateTime.class)) {
            setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        } else {
            setFieldValByName("updateTime", LocalDate.now(), metaObject);
        }
    }
}
